import React, { Component } from 'react';
import { connect } from 'dva';
import {
  Card,
  Badge,
  Divider,
  Button,
  Icon,
  Table,
  Skeleton,
  Row,
  Col,
  Modal,
  Form,
  Input,
  Select,
  message,
} from 'antd';
import DescriptionList from '@/components/DescriptionList';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import router from 'umi/router';
import moment from 'moment';
import styles from '../Less/BasicProfile.less';

const { Description } = DescriptionList;
const FormItem = Form.Item;

const CreateForm = Form.create()(props => {
  const { modalVisible, form, handleAdd, handleModalVisible } = props;

  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();
      handleAdd(fieldsValue);
    });
  };
  return (
    <Modal
      destroyOnClose
      title="分配账号"
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => handleModalVisible()}
    >
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="登录账号">
        {form.getFieldDecorator('name', {
          rules: [{ required: true, message: '请输入用户登录账号', min: 5 }],
        })(<Input placeholder="请输入用户登录账号" />)}
      </FormItem>
    </Modal>
  );
});

@connect(({ profile, loading }) => ({
  profile,
  loading: loading.effects['profile/fetchUserInfo'],
}))
class BasicProfile extends Component {
  constructor() {
    super();
    this.state = {
      visible: false,
      modalVisible: false,
    };
  }
  componentDidMount() {
    const { dispatch, match } = this.props;
    const { params } = match;
    dispatch({
      type: 'profile/fetchUserInfo',
      payload: params.id,
    });
  }
  showModal = () => {
    this.setState({
      visible: true,
    });
  };

  handleOk = e => {
    console.log(e);
    this.setState({
      visible: false,
    });
  };

  handleCancel = e => {
    console.log(e);
    this.setState({
      visible: false,
    });
  };

  handleModalVisible = flag => {
    this.setState({
      modalVisible: !!flag,
    });
  };
  handleAdd = fields => {
    const { dispatch } = this.props;
    const { profile = {} } = this.props;
    const { userInfo = {} } = profile;
    let formData = new FormData();
    formData.append('name', fields.name);
    formData.append('password', '12345678');
    formData.append('openid', userInfo.openid);
    formData.append('avatar', userInfo.avatar);
    formData.append('sex', userInfo.sex);
    formData.append('nickname', userInfo.nickname);
    formData.append('city', userInfo.city);
    formData.append('realname', userInfo.realname);
    formData.append('vip_level', userInfo.vip_level);
    dispatch({
      type: 'vip/fetchAddUserAccount',
      payload: formData,
      callback: () => {
        this.handleModalVisible();
        message.success('添加成功');
      },
    });
  };

  render() {
    const { profile = {}, loading } = this.props;
    const { contractOrder = [], userInfo = {} } = profile;
    const { modalVisible } = this.state;
    const parentMethods = {
      handleAdd: this.handleAdd,
      handleModalVisible: this.handleModalVisible,
    };
    const goodsInfo = data => {
      const goodsItem = data.map(item => (
        <li className={styles.goodsItem}>
          <Row gutter={18}>
            <Col span={3}>
              <img
                className={styles.goodImg}
                src={`https://lgjmall.lgjpt.com/attachment/${item.thumb}`}
                alt="商品图片"
              />
            </Col>
            <Col span={6}>
              <h4>{item.title}</h4>
              <h4>单价：￥{item.price}</h4>
              <h4>数量：{item.total}</h4>
              <h4>
                <b>总计</b>：￥{item.total * parseFloat(item.price)}
              </h4>
            </Col>
          </Row>
          <Divider />
        </li>
      ));
      return goodsItem;
    };
    const goodsColumns = [
      {
        title: '订单编号',
        dataIndex: 'id',
        key: 'id',
        render: text => <a onClick={() => router.push(`/wxuserlist/orderinfo/${text}`)}>{text}</a>,
      },
      {
        title: '订单编号',
        dataIndex: 'ordersn',
        key: 'ordersn',
      },
      {
        title: '合同编号',
        dataIndex: 'barcode',
        key: 'barcode',
      },
      {
        title: '单价',
        dataIndex: 'price',
        key: 'price',
        render: text => `￥${text}`,
      },
      {
        title: '支付时间',
        dataIndex: 'paytime',
        key: 'paytime',
        render: text => moment(text * 1000).format('YYYY-MM-DD HH:mm'),
      },
      {
        title: '数量（件）',
        dataIndex: 'num',
        key: 'num',
      },
      {
        title: '金额',
        dataIndex: 'amount',
        key: 'amount',
      },
    ];
    return (
      <PageHeaderWrapper title="基础详情页">
        <Card bordered={false}>
          <Skeleton loading={loading} active>
            <div>
              <div className={styles.avatarHolder}>
                <img alt="" src={userInfo.avatar} />
                <div className={styles.name}>{userInfo.name}</div>
              </div>
            </div>
            <DescriptionList size="large" title="用户信息" style={{ marginBottom: 32 }}>
              <Description term="昵称">{userInfo.nickname}</Description>
              <Description term="真实姓名">{userInfo.realname}</Description>
              <Description term="绑定电话">{userInfo.phone}</Description>
              <Description term="性别">
                {userInfo.sex === 1 ? (
                  <span>
                    <Icon type="man" twoToneColor="#eb2f96" />男
                  </span>
                ) : (
                  <span>
                    <Icon twoToneColor="#52c41a" type="woman" />女
                  </span>
                )}
              </Description>

              <Description term="状态">
                {userInfo.isblack === 0 ? (
                  <Badge status="processing" text="正常" />
                ) : (
                  <Badge status="error" text="已冻结" />
                )}
              </Description>
              <Description term="城市">{userInfo.city}</Description>

              <Description term="地址">{userInfo.address}</Description>
            </DescriptionList>
            <Divider />
            <DescriptionList size="large" title="vip信息" style={{ marginBottom: 32 }}>
              <Description term="会员类别">
                {userInfo.type === 0 ? '个人会员' : '企业会员'}
              </Description>
              <Description term="会员级别">{userInfo.vip_level}</Description>
              <Description term="会员到期时间">{userInfo.updated_at}</Description>
            </DescriptionList>

            <Divider />
            <DescriptionList size="large" title="相关操作" style={{ marginBottom: 32 }}>
              <Description term="开通会员">
                {' '}
                <Button size="small" type="primary">
                  开通会员
                </Button>
              </Description>
              <Description term="开通店铺">
                <Button size="small" type="primary" onClick={() => this.handleModalVisible(true)}>
                  开通店铺
                </Button>
              </Description>
              <Description term="续费会员">
                <Button size="small" type="primary">
                  续费会员
                </Button>
              </Description>
            </DescriptionList>
            <Divider style={{ marginBottom: 32 }} />
            <div className={styles.title}>合同订单</div>
            <Table
              style={{ marginBottom: 24 }}
              pagination={false}
              loading={loading}
              dataSource={contractOrder}
              columns={goodsColumns}
              rowKey="id"
              expandedRowRender={record => (
                <ul className={styles.goodsMap}>{goodsInfo(record.order_goods)}</ul>
              )}
            />
          </Skeleton>
          <CreateForm {...parentMethods} modalVisible={modalVisible} />
        </Card>
      </PageHeaderWrapper>
    );
  }
}

export default BasicProfile;
